package com.xiaozeng.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaozeng.param.AddressParam;
import com.xiaozeng.pojo.Address;
import com.xiaozeng.pojo.User;
import com.xiaozeng.user.mapper.AddressMapper;
import com.xiaozeng.user.service.AddressService;
import com.xiaozeng.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @Author: xiaozeng
 * @Date: 2022 11
 * @Description:
 **/
@Slf4j
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Result remove(Integer id) {
        //获取当前用户
        User user =(User) SecurityUtils.getSubject().getPrincipal();
        Integer a = addressMapper.selectById(id).getUserId();
        if(!a.equals(user.getUserId())){
            return Result.fail("参数异常,删除失败!");
        }
        int rows = addressMapper.deleteById(id);

        if (rows == 0){
            log.info("AddressServiceImpl.remove业务结束，结果:{}","地址删除失败");
            return Result.fail("删除地址数据失败!");
        }

        log.info("AddressServiceImpl.remove业务结束，结果:{}","地址删除成功!");
        return Result.ok("地址删除成功!");
    }

    @Override
    public Result save(AddressParam address) {
        //获取当前用户
        User user =(User) SecurityUtils.getSubject().getPrincipal();
        Address add = address.getAdd();
        add.setUserId(user.getUserId());

        //1.数据库插入
        int rows = addressMapper.insert(add);
        //2.返回结果处理
        if (rows == 0){
            return Result.fail("地址保存失败!");
        }
        log.info("AddressServiceImpl.save业务结束，结果:{}",address);
        //调用查询,返回全部数据!
        return list();
    }

    @Override
    public Result list() {
        User user =(User) SecurityUtils.getSubject().getPrincipal();
        //1,封装查询参数
        QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        List<Address> addressList = addressMapper.selectList(queryWrapper);

        //2.结果封装
        Result ok = Result.ok("查询成功", addressList);
        log.info("AddressServiceImpl.list业务结束，结果:{}",ok);
        return ok;
    }
}
